package updater.currency.convertor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;

import updater.currency.data.Currency;
import updater.currency.data.CurrencyName;
import updater.currency.rss.Feed;
import updater.currency.rss.FeedMessage;
import updater.currency.rss.RSSFeedParser;

public class ReadRSS {

	public void ReadAllCurrencyFromRSS() {
		ArrayList<CurrencyName> currencyNameList = GetCurrencyNameList("currency_list");
		for (int i = 0; i < currencyNameList.size(); i++) {
			String rssPath = "http://themoneyconverter.com/rss-feed/"
					+ currencyNameList.get(i).getSymbol() + "/rss.xml";
			RSSFeedParser parser = new RSSFeedParser(rssPath);
			Feed feed = parser.readFeed();
			Currency currency = ParseFeedMessageToCurrency(feed,
					currencyNameList.get(i).getName(), "Hong Kong Dollar");
			writeToXML(currency);
		}
	}

	public ArrayList<CurrencyName> GetCurrencyNameList(String fileName) {

		ArrayList<CurrencyName> currencyNameList = new ArrayList<CurrencyName>();

		String filePath = "Data/" + fileName;
		File file = new File(filePath);
		BufferedReader reader = null;
		try {

			reader = new BufferedReader(new FileReader(file));
			String tempString = null;

			while ((tempString = reader.readLine()) != null) {
				CurrencyName currency = new CurrencyName();

				String[] strings = tempString.split(" - ");
				currency.setSymbol(strings[0]);
				currency.setName(strings[1]);

				currencyNameList.add(currency);

			}
			reader.close();
		} catch (IOException e) {
			System.out.println("File not found");
		}
		return currencyNameList;
	}

	public Currency ParseFeedMessageToCurrency(Feed feed, String from, String to) {
		Currency currency = new Currency();

		for (FeedMessage message : feed.getMessages()) {
			String priceLine = message.getDescription();

			if (!priceLine.contains(to)) {
				continue;
			} else {

				String title = message.getTitle();
				String titleStrings[] = title.split("/");
				String symbol = titleStrings[1];
				String pubDate = message.getPubDate();
				String descStrings[] = priceLine.split(" = ");
				String price = descStrings[1].substring(0,
						descStrings[1].indexOf(to)).trim();

				currency.setCurrency(from, symbol, pubDate, price);

			}

		}
		return currency;

	}

	private void writeToXML(Currency currency) {

		XStream xstream = new XStream(new DomDriver());

		String filePath = "Data/" + currency.getSymbol() + ".xml";
		String currentPath = new File(filePath).getAbsolutePath();

		ArrayList<Currency> currencyList = ReadCurrencyFromXML(currency
				.getSymbol());

		if (currencyList.size() != 0
				&& DateChecker.isExistDateOfCurrency(currency, currencyList)) {
			return;
		}
		DateChecker.isExistDateOfCurrencyAndTheLeast(currency, currencyList);
		currencyList.add(currency);
		System.out.println(currentPath);
		try {
			FileOutputStream fs = new FileOutputStream(currentPath);
			xstream.toXML(currencyList, fs);
		} catch (FileNotFoundException e1) {
			System.out.println("File not found");
		}

	}

	public ArrayList<Currency> ReadCurrencyFromXML(String symbol) {

		XStream xs = new XStream(new DomDriver());
		ArrayList<Currency> currencyList = new ArrayList<Currency>();

		try {
			String filePath = "Data/" + symbol + ".xml";
			String currentPath = new File(filePath).getAbsolutePath();
			FileInputStream fis = new FileInputStream(currentPath);
			xs.alias("list", ArrayList.class);
			try {
				currencyList = (ArrayList<Currency>) xs.fromXML(fis);
			} catch (Exception ex1) {
				return currencyList;
			}
		} catch (FileNotFoundException ex) {
			System.out.println("Symbol is invalid. Cannot from this currency");
			return null;
		}
		return currencyList;
	}

	/*
	 * public void clearAllRecordInCurrency(String sybmol) {
	 * 
	 * String filePath = "Data/" + sybmol + ".xml"; String currentPath = new
	 * File(filePath).getAbsolutePath();
	 * 
	 * try {
	 * 
	 * FileOutputStream fs = new FileOutputStream(currentPath); try {
	 * fs.write((new String().getBytes())); fs.close(); } catch (IOException e)
	 * {
	 * 
	 * e.printStackTrace(); }
	 * 
	 * } catch (FileNotFoundException e1) { e1.printStackTrace(); }
	 * 
	 * }
	 */
}
